package
{
    import flash.display.MovieClip;
    import flash.display.Shape;
    import flash.utils.getTimer;

    [Embed(source="/../res/assets.swf", symbol="RabbitMC")]
    public class Rabbit extends MovieClip
    {
        private static const MOVE_SPEED : Number = 300.0;
        private static const JUMP_SPEED : Number = 400.0;
        private static const GRAVITY    : Number = 200.0;
        
        private var xTarget : Number;
        private var ySpeed  : Number;
        
        public var limit : Number;
        
        private var lastFrameTime : Number;
        
        private var m_onFallToTheGround : Function = null;
        
        public function Rabbit(onFallToTheGround : Function)
        {
            super();
            
            m_onFallToTheGround = onFallToTheGround;
            
            //addEventListener(Event.ENTER_FRAME, onEnterFrame);
            
            /*var circle : Shape = new Shape();
            circle.graphics.beginFill(0xFF0000);
            circle.graphics.drawCircle(0, 0, 32);
            circle.graphics.endFill();
            addChild(circle);*/
            
            xTarget = 0;
            ySpeed  = 0;
            
            lastFrameTime = flash.utils.getTimer();
        }
        
        public function moveTo(x_pos : Number) : void
        {
            xTarget = x_pos;
        }
        
        public function jump(byClick : Boolean = false) : Boolean
        {
            if(!byClick || (y == limit))
            {
                ySpeed = - JUMP_SPEED;
                return true;
            }
            return false;
        }
        
        public function tick() : void
        {
            const frameTime : Number = flash.utils.getTimer();
            const dt        : Number = frameTime - lastFrameTime;
            lastFrameTime = frameTime;
            
            const moveDistOnThisFrame : Number = MOVE_SPEED * dt / 1000.0;
            const distNeeded          : Number = xTarget - x;

            if(Math.abs(distNeeded) < moveDistOnThisFrame)
            {
                x = xTarget;
            }
            else
            {            
                if(distNeeded > 0)
                    x += moveDistOnThisFrame;
                else if(distNeeded < 0)
                    x -= moveDistOnThisFrame;
            }
            
            ySpeed += GRAVITY * dt / 1000.0;
            var new_y : Number = y + ySpeed * dt / 1000.0;
            
            if((y < limit) && (new_y >= limit))
            {
                m_onFallToTheGround();
            }

            y = new_y;
            if(y >= limit)
            {
                ySpeed = 0;
                y = limit;
            }
        }        
    }
}